//
//  userAccount.swift
//  Weibo007
//
//  Created by 闫崇 on 15/12/15.
//  Copyright © 2015年 闫崇. All rights reserved.
//


//保存用户的 token  就不需要每一次都去网络上加载
import UIKit

class userAccount: NSObject ,NSCoding{

    //用于调用access_token，接口获取授权后的access token。
    var access_token : String
    //access_token的生命周期，单位是秒数(实际上是数值)
    var expires_in : NSTimeInterval
    //当前授权用户的UID
    var uid : String
    
    //过期日期
    var expiresDate : NSDate
    
    //友好显示名称
    var name : String?
    
    //用户头像地址(大图)
    var avatar_large : String?
    
    
    
    init (dict:[String:AnyObject]){
        
        access_token = dict["access_token"] as! String
        
        expires_in = dict["expires_in"] as! NSTimeInterval
        
        uid = dict["uid"] as! String
        
        //计算过期日期
        expiresDate = NSDate(timeIntervalSinceNow: expires_in)
    }
    
    
    //打印对象信息
    override var description : String {
        let properties = ["access_token","expires_in","uid","expiresDate","avatar_large","name"]
        
        
        return "\(self.dictionaryWithValuesForKeys(properties))"
    }
    
    
    //打印用户信息
    func loadUserInfo(finish:(account:userAccount?,error:ErrorType?) -> ()) {
        
        
        let params = ["access_token":access_token,"uid":uid]
        
        NetworkTool.sharedNetworkTools().GET("2/users/show.json", parameters: params, success: { (_, JSON) -> Void in
            
            let dict = JSON as! [String : AnyObject]
            self.name = dict["name"] as? String
            self.avatar_large = dict["avatar_large"] as? String
            
            self.saveAccount()
            
            finish(account: self, error: nil)
            
            }) { (_, error) -> Void in
            finish(account: nil, error: error)
                
        }
    }
    
    
    
    
    //MARK - 保存和加载文件
    static let accountPath = (NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last! as NSString ).stringByAppendingPathComponent("account.plist")
    
    //将当前对象保存在沙盒当中
    func saveAccount() {
        
        print(userAccount.accountPath)
        
        NSKeyedArchiver.archiveRootObject(self, toFile: userAccount.accountPath)
        
    }
    
    //注意:如果之前没有归档可能会返回 nil 
    class func loadAccount () -> userAccount? {
        //判断token 是否已经过期,如果过期直接放回 nil 进入登陆界面
        if let account =  NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? userAccount{
            //判断日期是否过期,与当前系统时间作比较低于当前系统之间就认为过期
            //过期日期大于当前日期结果应该是降序
            if account.expiresDate.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                return account
            }
            
        }
        
        
        
        return nil
        
        
    }
    
    
    
    //MARK - 归档解档
    
    /**
     解档 :  aDecoder 解码器 就是把磁盘中的二进制文件转换成对象
     */
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as! String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as! String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as! NSDate
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        
    }
    
    /**
    归档 : aCoder 编码器就是把对象转换成二级制保存在磁盘中
     */
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        
    }
    
}
